﻿using Dapper;
using Mall.DomainModel;
using Mall.DomainModel.IRepository;
using Mall.Repository.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mall.Repository
{
    public class ShipperUserRepository : BaseRepository<ShipperUser, Guid>, IShipperUserRepository
    {
        public ShipperUserRepository(IDapperConfiguration configuration) : base(configuration)
        {
        }
        public async Task<ShipperUser> GetShipperUserByPhone(string phone, string name)
        {
            const string sql = @"SELECT Id,Phone,Name,IDCode,IDImg,IDImgBack,IDCertificationTime,Enabled,HeadImg,IsReal,LastLoginTime,Sex FROM ShipperUsers WHERE Phone = @Phone  AND Name = @Name AND Enabled = 1"; // 只查询启用的用户

            var parameters = new DynamicParameters();
            parameters.Add("Phone", phone, DbType.String);
            //parameters.Add("Password", password, DbType.String);
            parameters.Add("Name", name, DbType.String);

            try
            {
                using (ReadConnection)
                {
                    var user = await ReadConnection.QueryFirstOrDefaultAsync<ShipperUser>(sql, parameters);

                    if (user != null)
                    {
                        // 更新最后登录时间
                        await UpdateLastLoginTime(user.Id);
                    }

                    return user;
                }
            }
            catch (Exception ex)
            {
                // 记录日志
                Console.WriteLine($"登录查询失败: {ex.Message}");
                return null;
            }
        }
        private async Task UpdateLastLoginTime(Guid userId)
        {
            const string updateSql = "UPDATE ShipperUsers SET LastLoginTime = @Now WHERE Id = @Id";

            await WriteConnection.ExecuteAsync(updateSql, new
            {
                Id = userId,
                Now = DateTime.Now
            });
        }

    }
}
